package entity;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * 描述
 *
 * @author www.itheima.com
 * @version 1.0
 * @package entity *
 * @since 1.0
 */
public class JwtUtil {
    //签名私钥
    private static String key = "8a1a203f-6443-438e-aa43-25d9c3fd54a0";
    //签名的失效时间
    private static Long ttl = (long)1000 * 60 * 60 * 24;

    /**
     * @Description 设置认证token
     * @Param [id,登陆用户id name登陆用户名]
     * @Return : java.lang.String
     * @Author : dunn
     *
     */
    public static String createJwt(String id,String name){

        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")

                .setSubject("yuelife")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + ttl))

                //用户信息
                .claim("id", id)
                .claim("name", name)

                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
        return token;
    }

    /**
     * @Description 解析token字符串获取claims
     * @Param [token]
     * @Return : io.jsonwebtoken.Claims
     * @Author : dunn
     *
     */
    public static Claims parseJwt(String token){
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        System.out.println(claims.getExpiration());
        long time = claims.getExpiration().getTime()-System.currentTimeMillis();
        System.out.println(time);
        return claims;
    }

    /**
     * 判断token是否有效
     * @param token
     * @return
     */
    public static boolean checkToken(String token) {
        if(StringUtils.isEmpty(token)) return false;
        try {
            Jwts.parser().setSigningKey(key).parseClaimsJws(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String dyy = createJwt("1", "dyy");
        System.out.println(dyy);
    }
}
